// 获取最大公约数
function getGcd(a, b) {
  let n1, n2
  if (a > b) {
    n1 = a
    n2 = b
  } else {
    n1 = b
    n2 = a
  }
  const remainder = n1 % n2
  if (remainder === 0) {
    return n2
  } else {
    return getGcd(n2, remainder)
  }
}
// 创建虚拟dom 并且放回对应的值
const checkSize = async(files, isVideo) => {
  if (!files || !files[0]) return false
  const checktimevideo = document.getElementById('checktimevideo')
  if (checktimevideo) {
    document.body.removeChild(checktimevideo)
  }
  let doms
  if (!isVideo) {
    doms = document.createElement('video')
  } else {
    doms = document.createElement('audio')
  }
  const url = URL.createObjectURL(files[0])
  doms.src = url
  doms.id = 'checktimevideo'
  doms.style.display = 'none'
  document.body.appendChild(doms)
  return await gettime(doms)
}
export const getVideoDuration = async(file, isVideo) => {
  if (!file) return false
  const checktimevideo = document.getElementById('checktimevideo')
  if (checktimevideo) {
    document.body.removeChild(checktimevideo)
  }
  let doms
  if (!isVideo) {
    doms = document.createElement('video')
  } else {
    doms = document.createElement('audio')
  }
  const url = URL.createObjectURL(file)
  doms.src = url
  doms.id = 'checktimevideo'
  doms.style.display = 'none'
  document.body.appendChild(doms)
  return await gettime(doms)
}
const gettime = (doms) => {
  // 由于loadedmetadata 是异步代码所以需要promise进行封装转换为同步代码执行
  const promise = new Promise((resolve) => {
    doms.addEventListener('loadedmetadata', (e) => {
      const gcd = getGcd(e.target.videoWidth, e.target.videoHeight)
      const obj = {
        width: doms.videoWidth, // 尺寸宽 --- 分辨率
        height: doms.videoHeight, // 尺寸高
        duration: Number(e.target.duration.toFixed(2)), // 视频时长 1表示一秒
        ccbl: [e.target.videoWidth / gcd, e.target.videoHeight / gcd] // 计算尺寸比例
      }
      resolve(obj)
    })
  })
  return promise
}
export const bytesToSize = (size) => {
  if (size < 0.1 * 1024) {
    // 小于0.1KB，则转化成B
    size = size.toFixed(2) + 'B'
  } else if (size < 0.1 * 1024 * 1024) {
    // 小于0.1MB，则转化成KB
    size = (size / 1024).toFixed(2) + 'KB'
  } else if (size < 0.1 * 1024 * 1024 * 1024) {
    // 小于0.1GB，则转化成MB
    size = (size / (1024 * 1024)).toFixed(2) + 'MB'
  } else {
    // 其他转化成GB
    size = (size / (1024 * 1024 * 1024)).toFixed(2) + 'GB'
  }

  // 转成字符串
  const sizeStr = size + ''
  // 获取小数点处的索引
  const index = sizeStr.indexOf('.')
  // 获取小数点后两位的值
  const dou = sizeStr.substr(index + 1, 2)

  // 判断后两位是否为00，如果是则删除00
  if (dou === '00') { return sizeStr.substring(0, index) + sizeStr.substr(index + 3, 2) }

  return size
}
export default checkSize
